package at.jku.pervasive.filter;

import java.util.LinkedList;

import at.jku.pervasive.Position;

public class MeanFilter implements Filter
{

	/**
	 * Calculates the mean of all positions and replaces the first value of the
	 * list with the mean.
	 * @see at.jku.pervasive.filter.Filter#applyFilter(java.util.LinkedList)
	 */
	@Override
	public LinkedList<Position> applyFilter(LinkedList<Position> lastPositions)
	{
		double x = 0.0;
		double y = 0.0;
		double z = 0.0;

		// iterate over each position and calculate sum
		for (Position position : lastPositions)
		{
			x += position.getX();
			y += position.getY();
			z += position.getZ();
		}

		// calculate the mean
		double count = lastPositions.size();
		x /= count;
		y /= count;
		z /= count;

		// create new position with given id
		Position recentPosition = lastPositions.getFirst();
		Position meanPosition = new Position(recentPosition.getId(), x, y, z, false, recentPosition.getDate());

		// create a copy of the position list and replace the recent position
		// with the calculated
		LinkedList<Position> clone = (LinkedList<Position>) lastPositions.clone();
		clone.set(0, meanPosition);
		return clone;
	}

}
